from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .. models import Types
import os,time
from django.core.paginator import Paginator

def typeadd(request):
    # 查询所有分类
    ob = Types.objects.all()
    context = {'types':ob}
    return render(request,'myadmin/type/typeadd.html',context)
def typeinsert(request):
    try:
        ob = Types()
        ob.name = request.POST['name']
        ob.pid = request.POST['pid']
        # 判断是否为顶级分类
        if ob.pid == '0':
            ob.path = '0,' 
        else:
            p = Types.objects.get(id=ob.pid)
            ob.path = p.path+ob.pid+','
        ob.save()

        return HttpResponse('<script>alert("添加成功");location.href="/myadmin/typelist"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="/myadmin/typeadd"</script>')

def typelist(request):
    v = request.GET.get('keywords','')
    from django.db.models import Q
    ob = Types.objects.filter(Q(id__contains=v)|Q(name__contains=v)).extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    for x in ob:
        n = len(x.path) - 2
        x.name = (n*'──')+x.name
     # 实例化分页类
    paginator = Paginator(ob,8)
    
    # 获取当前页码
    p = int(request.GET.get('p',1))

    # 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
    userlist= paginator.page(p)
    # 分配数据
    context = {'typeinfo':userlist,'p':p}

    # 加载模板
    return render(request,'myadmin/type/typelist.html',context)

def typetall():
    
    ob = Types.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')  
    for x in ob:
        n = len(x.path) - 2
        x.name = (n*'──')+x.name

    return ob
# 删除分类    
def typedel(request,uid):
    # 判断当前分类下是否存在子类
    num = Types.objects.filter(pid=uid).count()
    if num:
        # 有子类,不能删除
        return HttpResponse('<script>alert("当前分类下,还有子类,不能删除");location.href="/myadmin/typelist"</script>')
    else:
        # 如果没有子类,还要判断当前类下是否有商品发布,
        ob = Types.objects.get(id=uid)
        g = ob.goods_set.all().count()
        if g:
            return HttpResponse('<script>alert("当前分类下,还有商品,不能删除");location.href="/myadmin/typelist"</script>')
        else:
            # 可以删除
            ob.delete() 
    return HttpResponse('<script>alert("删除成功");location.href="/myadmin/typelist"</script>')
def typeedit(request,uid):
    obs = typetall()
    # 查询当前的分类信息
    ob = Types.objects.get(id=uid)
    # 分配数据
    context = {'tinfo':ob,'typelist':obs}

    # 加载模板
    return render(request,'myadmin/type/typeedit.html',context)
def typeupdate(request):
    ob = Types.objects.get(id=request.POST['tid'])
    ob.name = request.POST['name']
    ob.save()
    return HttpResponse('<script>alert("修改成功");location.href="/myadmin/typelist"</script>')
   